
	Ext.namespace("panel.widgets.selection");
	
	panel.widgets.selection = function(config) {
		
		/**
		 * Config 
		**/
		config       = Ext.value(config, {});
		config.hooks = Ext.value(config.hooks, {});
		config.hooks.dataIndex = Ext.value(config.hooks.dataIndex, {});
		
		config.useCheckboxes = Ext.value(config.useCheckboxes, true);
		config.useSelection  = Ext.value(config.useSelection,  true);
		config.statusbar     = Ext.value(config.statusbar,     true);
		
		/**
		 * Widget 
		**/
		var state  = {}; 
		var widget = {};
		
		/**
		 * Widget ID 
		**/
		widget.id = Ext.value(config.id, "PW:selection:" + Ext.id());
		
		/**
		 * Listeners/Observer
		**/
		
		widget.observer = new Ext.util.Observable();
		
		widget.observer.addEvents({
			
			"selection" : true,
			"init"      : true
			
		});
		
		$H(config.listeners).each( function(f, e) {
			
			widget.observer.on(e, f);
			
		});
		
		/**
		 * Selection: 
		**/
		widget.selection = {};
		
		widget.selection.init = function() {
			
//			panel.console.log(widget.id, "INIT");
			
			/**
			 * Selection change event 
			**/
			
			var _fe = function() {
				
				widget.observer.fireEvent("selection", widget.selection);
			
			};
						
			if( config.useCheckboxes ) {
				
				widget.check_model.column.observer.on("change",   _fe);
				widget.check_model.column.observer.on("hdchange", _fe);
				
			}	// if
			
			if( config.selectionModel && config.useSelection ) {
				
				config.selectionModel.on("selectionchange", _fe);
				
			}	// if
			
			delete _fe;
			
		};
		
		widget.observer.on("init", widget.selection.init);
		
		widget.hasSelection = function(type) {
			
			var sm = (config.selectionModel instanceof Function) ? 
				config.selectionModel() : 
				config.selectionModel
			;
			
			switch( type ) {
				
			case "checked":
				return config.useCheckboxes ? widget.check_model.column.hasChecked() : false;
				break;
				
			case "selected":
				return config.useSelection ? ( sm && sm.hasSelection() ) : false;
				break;
			
			default:
			
				return ( 
					( config.useCheckboxes ? widget.check_model.column.hasChecked() : false ) || 
					( config.useSelection  ? ( sm && sm.hasSelection() ) : false )
				);
				
				break;
			
			}	// switch 
			
		};
		
		widget.getSelections = function(type) {
			
			switch( true ) {
				
			case (
				config.useCheckboxes                     &&
				(type == undefined || type == "checked") && 
				widget.check_model.column.hasChecked()
			):
				
				return config.store.query("is_checked", true).getRange();
				
				break;
				
			case (
				config.useSelection                       &&
				(type == undefined || type == "selected") && 
				( config.selectionModel && config.selectionModel.hasSelection() )
			):

				return config.selectionModel.getSelections();
				
				break;
				
			default:
				return [];
				break;
				
			}	// switch
						
		};
		
		widget.setSelections = function(records, state, type) {
	
			var state = Ext.value(state, true);
	
			switch( true ) {
				
			case ( config.useSelection && type == "select" && (config.selectionModel instanceof Ext.grid.RowSelectionModel ) ):

				if( state ) {
					
					config.selectionModel.selectRecords(records);
					
				} else {
					
					records.each( function(record) {
					
						config.selectionModel.deselectRow( record.store.indexOf(record) );
						
					} );
					
				}	// if
			
				break;
				
			case ( config.useCheckboxes ):
			
				widget.check_model.column.checkRecords(records, state);
				config.store.fireEvent("datachanged");
			
				break;
				
			}	// switch			
				
			widget.observer.fireEvent("selection");
			
		};
		
		widget.clearSelections = function() {
			
//			panel.console.log(widget.id, "A", "CLEAR");
			
			if( config.useCheckboxes && widget.hasSelection("checked") ) {
				
				
				widget.check_model.column.checkRecords( config.store.getRange(), false );
				config.store.fireEvent("datachanged");
				
				
			}	// if
			
			if( config.useSelection ) {
				
				config.selectionModel.clearSelections(true);
				
			}	// if
			
			widget.observer.fireEvent("selection");
			
		};
		
		/**
		 * Check model 
		**/
		if( config.useCheckboxes ) {
		
			widget.check_model = {};
	
			config.hooks.check_model_column_config              = Ext.value( config.hooks.check_model_column_config, {});
			config.hooks.check_model_column_config.menuDisabled = Ext.value( config.hooks.check_model_column_config.menuDisabled, true);
			config.hooks.check_model_column_config.sortable     = Ext.value( config.hooks.check_model_column_config.sortable, false);
			
			widget.check_model.column = 
			panel.widgets.chunks.grid.columns.is_checked( config.hooks.check_model_column_config );		
			
			widget.check_model.buttons = {};
			widget.check_model.buttons.clear = new Ext.Button({
				
				iconCls : "icon_action_clear_checked",
				text    : "Uncheck all",
				hidden  : true,
				handler : function() {
					
					widget.clearSelections();
					
				}
				
			});
			
			var _fe  = function() {
				
				widget.check_model.buttons.clear.setVisible( widget.hasSelection("checked") );
				
			};
			
			widget.observer.on("selection", _fe);
			config.store.on("remove", _fe);
			config.store.on("add", _fe);
			config.store.on("load", _fe);
			config.store.on("clear", _fe);
			
			widget.observer.on("init", function() {

				if( config.useSelection && (config.selectionModel instanceof Ext.grid.RowSelectionModel)  ) {
					
					widget.check_model.column.observer.on("change", function(column, store, record, value, dataIndex) {
						
						config.selectionModel.selectRecords([record]);
						
					});
	
				}	// if
				
			});
			
		}	// if
		
		/**
		 * Statusbar 
		**/
		
		widget.checkStatus = config.checkStatus || function() {
			
			if( !config.statusbar ) {
				return; }
				
			//panel.console.log(widget.id, "check_status");
			
			if( !widget.hasSelection() ) {
							
				var status = "";
				
			} else {
				
				if( widget.getSelections().length == 1 ) {
					
					var dataIndex = Ext.value(config.hooks.dataIndex.title, "title");
					
					if( dataIndex instanceof Function ) {
					
						var status = "You have selected: <b>" + dataIndex(widget.getSelections()[0]) + "</b>.";
					
					} else {
						
						var status = "You have selected: <b>" + widget.getSelections()[0].data[dataIndex] + "</b>.";
						
					}	// if
					
				} else {
				
					var status = "You have selected: <b>" + widget.getSelections().length + "</b> item(s)."; 
					
				}	// if
				
			}	// if
			
			if( status.length && widget.statusbar.bar.rendered ) {
			
				widget.statusbar.bar.setStatus({
						
					text: [
						
						"<div class='icon_ icon_information f_l p_r5'></div>", 
						"<div>", status ,"</div>"
						
					].join("")
					
				});
				
			} else if( widget.statusbar.bar.rendered ) {
				
				widget.statusbar.bar.clearStatus();
				
			}	// if
			
		};
		
		if( config.statusbar ) {
		
			widget.statusbar = {};
			
			widget.statusbar.bar = {
					
				statusAlign: "left",
				defaultText: "",
				
				items: []
				
			};
			
			if( config.useCheckboxes ) {
				widget.statusbar.bar.items.push(widget.check_model.buttons.clear); }
			
			widget.statusbar.bar = new Ext.StatusBar(widget.statusbar.bar);
			
			widget.statusbar.init = function() {
				
				widget.observer.on("selection", widget.checkStatus);
				
			};
			
			widget.observer.on("init", widget.statusbar.init);
			
			
		}	// if				
			
		
		widget.init = function() {
			
			/**
			 * 1. Do init.
			 * 2. Avoid reinitialization if defined 
			**/

			if( !state.init ) {
			
				if( config.useSelection ) {
					
					if( config.selectionModel instanceof Function ) {
						config.selectionModel = config.selectionModel(); }
												
				}	// if
					
				widget.observer.fireEvent("init");
				
				state.init = true;
				
			}	// if
			
		};
		
		return widget;
		
	};